package com.example.coding_problem.Fragment;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.coding_problem.Life_assistant_SQL;
import com.example.coding_problem.Life_assistant_list;
import com.example.coding_problem.MainActivity;
import com.example.coding_problem.MyApplicayion;
import com.example.coding_problem.R;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;

public class Life_assistant extends Fragment {
    private static final String TAG = "Life_assistant";
    private TabLayout life_tabLayout_main;
    private ViewPager life_viewPager_main;
    private FragmentManager fm;
    private int i = 0;
    private int j=0;
    private int k=0;
    private TextView lift_tv_wd;
    private TextView lift_tv_wd1;
    private ImageView iv_refresh;
    private Life_assistant_SQL dbHelper;
    private LineChart broken_line;
    private ArrayList<Entry> pointValues = new ArrayList<>();
    private List<Life_assistant_list> life_assistant_list = new ArrayList<>();
    private TextView tv_life_index1;
    private TextView tv_life_index;
    private TextView tv_life_index2;
    private TextView tv_life_index3;
    private TextView tv_life_index4;
    public Life_assistant() {
    }
    public interface BlogService {
        @GET("getAirCondition")
        Call<ResponseBody> getLog();
    }
    String[] name = {"昨天", "今天", "明天", "星期五", "星期六", "星期天"};
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            life_assistant_list=new ArrayList<>();
            initData(broken_line);
            handler.postDelayed(this, 3000);
        }
    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.life_assistant, container, false);
        initView(view);
        initChart();
        initViewLine(view);
        fm=getChildFragmentManager();
        initviewpager(view);
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, 3000);
        return view;
    }
    private void  initlife_SQL(){
       SQLiteDatabase db=dbHelper.getWritableDatabase();
       ContentValues values=new ContentValues();
       //传入数据
        values.put("wendu",life_assistant_list.get(0).get温度());
        values.put("pm2_5",life_assistant_list.get(0).get_$Pm256());
        values.put("xdsd",life_assistant_list.get(0).get相对湿度());
        values.put("cq2",life_assistant_list.get(0).getCo2());
        db.insert("Book",null,values);
        Cursor cursor=db.query("Book",null,null,null,null,null,null);
        //判断如果数据库里面的数据大于20条，则光标移至最后一行，然后获取id的位置，假如id为50则50-20=30，就要删除30行来确保只保存20行
        if(cursor.getCount()>20){
            cursor.moveToLast();
            i = cursor.getInt(cursor.getColumnIndex("id"));
            db.delete("Book","id<=?",new String[]{(cursor.getInt(cursor.getColumnIndex("id"))-20)+""});
        }
        //关闭光标，否则下次从上次光标数据开始读取
        cursor.close();
    }
    private void initviewpager(View view){
        life_tabLayout_main=(TabLayout)view.findViewById(R.id.life_tabLayout_main);
        life_viewPager_main=(ViewPager) view.findViewById(R.id.life_viewpager_main);
        List<Fragment>life_fragmentList=new ArrayList<>();
        life_fragmentList.add(new Life_LineChart1());
        life_fragmentList.add(new Life_LineChart2());
        life_fragmentList.add(new Life_LineChart());
        life_fragmentList.add(new Life_LineChar3());
        String[] stringsTools1={"空气质量","温度","相对湿度","二氧化碳"};
        ViewPagerAdapter1 adapter1=new ViewPagerAdapter1(fm,life_fragmentList,stringsTools1);
        life_viewPager_main.setOffscreenPageLimit(life_fragmentList.size()-1);
        life_viewPager_main.setAdapter(adapter1);
        life_tabLayout_main.setTabMode(TabLayout.MODE_FIXED);
        //绑定TabLayout和ViewPager
        life_tabLayout_main.setupWithViewPager(life_viewPager_main);
    }
    private void initViewLine(View view) {
        //设置折线图的数据
        initData(broken_line);
    }
    private void initView(View view) {
        broken_line = view.findViewById(R.id.broken_line);
        lift_tv_wd = (TextView) view.findViewById(R.id.lift_tv_wd);
        lift_tv_wd1 = (TextView) view.findViewById(R.id.lift_tv_wd1);
        iv_refresh = (ImageView) view.findViewById(R.id.life_iv_refresh);
        tv_life_index1 = (TextView) view.findViewById(R.id.tv_life_index1);
        tv_life_index = (TextView) view.findViewById(R.id.tv_life_index);
        tv_life_index2 = (TextView) view.findViewById(R.id.tv_life_index2);
        tv_life_index3 = (TextView) view.findViewById(R.id.tv_life_index3);
        tv_life_index4 = (TextView) view.findViewById(R.id.tv_life_index4);
        iv_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                j=0;
                k=1;
                life_assistant_list = new ArrayList<>();
                initData(broken_line);
            }
        });
    }

    private void initChart() {
        broken_line.animateXY(1000, 1000);
        //=========================设置图例=========================
        // 像"□ xxx"就是图例
        Legend legend = broken_line.getLegend();
        //设置图例显示在chart那个位置 setPosition建议放弃使用了
        //设置垂直方向上还是下或中
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        //设置水平方向是左边还是右边或中
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        //设置所有图例位置排序方向
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //设置图例的形状 有圆形、正方形、线
        legend.setForm(Legend.LegendForm.CIRCLE);
        //是否支持自动换行 目前只支持BelowChartLeft, BelowChartRight, BelowChartCenter
        legend.setWordWrapEnabled(true);
        //=======================设置X轴显示效果==================
        XAxis xAxis = broken_line.getXAxis();
        //是否启用X轴
        xAxis.setEnabled(true);
        //是否绘制X轴线
        xAxis.setDrawAxisLine(true);
        //设置X轴上每个竖线是否显示
        xAxis.setDrawGridLines(false);
        //设置是否绘制X轴上的对应值(标签)
        xAxis.setDrawLabels(true);
        //设置X轴显示位置
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置竖线为虚线样式
        // xAxis.enableGridDashedLine(10f, 10f, 0f);
        //设置x轴标签数
        xAxis.setLabelCount(20, true);
        //图表第一个和最后一个label数据不超出左边和右边的Y轴
        // xAxis.setAvoidFirstLastClipping(true);
        //设置限制线 12代表某个该轴某个值，也就是要画到该轴某个值上
        LimitLine limitLine = new LimitLine(12);
        //设置限制线的宽
        limitLine.setLineWidth(1f);
        //设置限制线的颜色
        limitLine.setLineColor(Color.RED);
        xAxis.setGranularity(0);     //这个很重要
//        //自定义x轴
//        xAxis.setValueFormatter(new IAxisValueFormatter() {
//            @Override
//            public String getFormattedValue(float value, AxisBase axis) {
//                return name[(int) value];
//            }
//        });
        //设置基线的位置
        limitLine.setLabelPosition(LimitLine.LimitLabelPosition.LEFT_TOP);
        limitLine.setLabel("马丹我是基线，也可以叫我水位线");
        //设置限制线为虚线
        limitLine.enableDashedLine(10f, 10f, 0f);
        //=================设置左边Y轴===============
        YAxis axisLeft = broken_line.getAxisLeft();
        //是否启用左边Y轴
        axisLeft.setEnabled(true);
        //设置最小值（这里就按demo里固死的写）
        axisLeft.setAxisMinimum(1);
        //设置最大值（这里就按demo里固死的写了）
        axisLeft.setAxisMaximum(50);
        //设置横向的线为虚线
        axisLeft.enableGridDashedLine(10f, 10f, 0f);
        //axisLeft.setDrawLimitLinesBehindData(true);
        //====================设置右边的Y轴===============
        YAxis axisRight = broken_line.getAxisRight();
        //是否启用右边Y轴
        axisRight.setEnabled(false);
        //设置最小值（这里按demo里的数据固死写了）
        axisRight.setAxisMinimum(1);
        //设置最大值（这里按demo里的数据固死写了）
        axisRight.setAxisMaximum(20);
        //设置横向的线为虚线
        axisRight.enableGridDashedLine(10f, 10f, 0f);
    }

    private void initData(final LineChart broken_line) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        BlogService service = retrofit.create(BlogService.class);
        Call<ResponseBody> call = service.getLog();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Gson gson = new Gson();
                try {
                    Life_assistant_list carlist = gson.fromJson(response.body().string(), Life_assistant_list.class);
                    pointValues.add(new Entry(i, carlist.get温度()));
                    //获取折线图数据
                    LineDataSet set1 = new LineDataSet(pointValues, "");
                    LineData data = new LineData(set1);
                    //设置折线颜色
                    set1.setColor(Color.parseColor("#6950a1"));
                    set1.setValueTextSize(10);
                    broken_line.setData(data); //设置数据
                    life_assistant_list.clear();
                    life_assistant_list.add(carlist);
                    dbHelper=new Life_assistant_SQL(MyApplicayion.getContext(),"BookStore.db",null,2);
                    initlife_SQL();
                    int min=0;
                    int max=15;
                    Random random=new Random();
                    int num = random.nextInt(max)%(max-min+1) + min;
                    if (j==0){
                        j=1;
                        lift_tv_wd.setText(life_assistant_list.get(0).get温度() + "°");
                        lift_tv_wd1.setText("今天:"+num+"-" + life_assistant_list.get(0).get温度() + "℃");
                    }
                    if (k==0){
                        if (life_assistant_list.get(0).get紫外线强度()<1000){
                            tv_life_index.setText("弱("+life_assistant_list.get(0).get紫外线强度()+")"+"\n"+"辐射较弱,涂擦SPE12~15、PA+护肤品");
                        }else if (life_assistant_list.get(0).get紫外线强度()>=1000&&life_assistant_list.get(0).get紫外线强度()<=3000){
                            tv_life_index.setText("中等("+life_assistant_list.get(0).get紫外线强度()+")"+"\n"+"涂擦SPE>15、PA+防晒护肤品");
                        }else if (life_assistant_list.get(0).get紫外线强度()>3000){
                            tv_life_index.setText("强("+life_assistant_list.get(0).get紫外线强度()+")"+"\n"+"尽量减少外出,需要涂抹高倍数防晒霜");
                        }
                            if (life_assistant_list.get(0).get温度() < 8) {
                                tv_life_index1.setText("较易发(" + life_assistant_list.get(0).get温度()+")" + "\n" + "温度低,风较大,较容易发生感冒,注意防护");
                            } else if (life_assistant_list.get(0).get温度() >= 8) {
                                tv_life_index1.setText("少发(" + life_assistant_list.get(0).get温度() +")"+ "\n" + "五明显降温,感冒几率较低");
                            }
                            if (life_assistant_list.get(0).get温度()<12){
                                tv_life_index2.setText("冷(" + life_assistant_list.get(0).get温度()+")" + "\n" + "建议穿长袖衬衫,单裤等服饰");
                            }else if (life_assistant_list.get(0).get温度()>=12&&life_assistant_list.get(0).get温度()<=21){
                                tv_life_index2.setText("舒适(" + life_assistant_list.get(0).get温度()+")" + "\n" + "建议穿短袖衬衫,单裤等服饰");
                            }else if (life_assistant_list.get(0).get温度()>=21){
                                tv_life_index2.setText("热(" + life_assistant_list.get(0).get温度()+")" + "\n" + "建议穿T恤,短薄外套等夏季服饰");
                            }
                            if (life_assistant_list.get(0).getCo2()<3000){
                                tv_life_index3.setText("事宜(" + life_assistant_list.get(0).getCo2()+")" + "\n" + "气候适宜,推荐您进行户外运动");
                            }else if (life_assistant_list.get(0).getCo2()>=3000&&life_assistant_list.get(0).getCo2()<=6000){
                                tv_life_index3.setText("中(" + life_assistant_list.get(0).getCo2()+")" + "\n" + "易感人群应适当减少室外活动,推荐您进行户外运动");
                            }else if (life_assistant_list.get(0).getCo2()>6000){
                                tv_life_index3.setText("较不宜(" + life_assistant_list.get(0).getCo2()+")" + "\n" + "空气氧气含量低,请在室内进行休闲运动");
                            }
                            if (life_assistant_list.get(0).get_$Pm256()<30){
                                tv_life_index4.setText("优(" + life_assistant_list.get(0).get_$Pm256()+")" + "\n" + "空气质量非常好,非常适合户外活动，趁机出去多呼吸新鲜空气");
                            }else   if (life_assistant_list.get(0).get_$Pm256()>=30&&life_assistant_list.get(0).get_$Pm256()<=100){
                                tv_life_index4.setText("良(" + life_assistant_list.get(0).get_$Pm256()+")" + "\n" + "易感人群应适当减少室外活动,推荐您进行户外运动");
                            }else   if (life_assistant_list.get(0).get_$Pm256()>100){
                                tv_life_index4.setText("污染(" + life_assistant_list.get(0).get_$Pm256()+")" + "\n" + "空气质量低,不适合户外运动");
                            }
                    }
                    k=0;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
}
